#pragma once

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <functional>
#include <unordered_map>
#include <strings.h>
#include "log.hpp"

extern Log lg;

const uint16_t DEFAULT_PORT = 8888;
const size_t BUFFER_SIZE = 1024;

// using func_t = std::function<std::string(const std::string&)>;
using func_t = std::function<std::string(const std::string&, const std::string&, uint16_t)>;

class udpServer
{
public:
    udpServer(uint16_t port = DEFAULT_PORT)
        :_sockfd(0),
        _port(port),
        _is_running(false)
    { }

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); //创建套接字fd
        if(_sockfd < 0) { 
            lg(FATAL, "socket err, errno:%d, errmsg:%s", errno, strerror(errno));
            exit(1);
        }
        else { lg(LOG, "socket success"); }
        struct sockaddr_in local; //设置sock
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        //绑定IP和端口号
        if(bind(_sockfd, (const sockaddr*)&local, sizeof(local)) < 0) {
            lg(FATAL, "bind err, errno:%d, errmsg:%s", errno, strerror(errno));
            exit(1);
        }
        else {
            lg(LOG, "bind success, errno:%d, errmsg:%s", errno, strerror(errno));
        }
    }

    void run(func_t func)
    {
        _is_running = true;
        // lg(LOG, "begin run");
        char buffer[BUFFER_SIZE];
        while(_is_running)
        {
            struct sockaddr_in client;
            bzero(&client, sizeof(client));
            socklen_t len = sizeof(client);
            // lg(LOG, "begin recvfrom");
            //接收信息
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client, &len);
            std::string clientip = inet_ntoa(client.sin_addr);
            uint16_t clientport = ntohs(client.sin_port);
            if(s < 0) {
                lg(WARNING, "recvfrom err, errno:%d, errmsg:%s", errno, strerror(errno));
                continue;
            }
            else if (s == 0) {
                // 对方发送空数据 -> 关闭对该客户端的管理
                std::cout << "clinet closed, ip: " << clientip << std::endl;
                auto iter = _usrs.find(std::string(clientip));
                if (iter != _usrs.end()) {
                    _usrs.erase(iter);
                }
            }
            else {
                lg(LOG, "recvfrom success, errno:%d, errmsg:%s", errno, strerror(errno));
            }
            check_usr(clientip, clientport); //用户检查
            //加工信息
            buffer[s] = 0;
            std::string msg = func(std::string(buffer), clientip, clientport);
            std::cout << msg << std::endl;

            boardcast(msg); //广播信息
        }
    }

    ~udpServer()
    {
        close(_sockfd);
    }

private:
    void boardcast(std::string& msg)
    {
        for(auto usr : _usrs)
        {
            std::string usrip = usr.first;
            std::string usrport = usr.second;
            sockaddr_in client; memset(&client, 0, sizeof(client));
            client.sin_family = AF_INET;
            client.sin_addr.s_addr = inet_addr(usrip.c_str());
            client.sin_port = htons(atoi(usrport.c_str()));
            ssize_t s = sendto(_sockfd, msg.c_str(), msg.size(), 0, (const sockaddr*)&client, (socklen_t)sizeof(client));
            if(s < 0) {
                lg(WARNING, "send to %s err, errno:%d, errmsg:%s", usrip.c_str(), errno, strerror(errno));
                continue;
            }
            else {
                lg(LOG, "send to %s success, errno:%d, errmsg:%s", usrip.c_str(), errno, strerror(errno));
            }
        }
    }

    void check_usr(const std::string& ip, uint16_t port)
    {
        if(_usrs.find(ip) == _usrs.end()) {
            std::cout << "new clinet, ip: " << ip << std::endl;
            _usrs.insert(std::make_pair(ip, std::to_string(port)));
        }
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _is_running;
    std::unordered_map<std::string, std::string> _usrs; //ip - port
};
